/**
 * 获取函数调用关系测试用例
 *
 * Created by yangyunze on 2021/11/23.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));

const common = require('./../../../common');
const Administrator = require('./../../../../models/administrator');
const uri = require('./../../uri');
const benchmark = require('./../../../../benchmark/integration-test/main');

module.exports = describe('/GET /functions/:functionId/invokes.json', function () {
  const administrator = new Administrator();
  let projectVersion = {};
  const newUserIds = [];
  let mainFuncId;
  let fileAlternativeFunc;
  function url(functionId) {
    return `/functions/${functionId}/invokes.json`;
  }

  function invokeFilesUrl(functionId, mangledId) {
    return `/functions/${functionId}/integration-functions/${mangledId}/invoke-files.json`;
  }

  function stubUrl(functionId) {
    return `/functions/${functionId}/integration-functions/stubs.json`;
  }
  function removeFuncParams(funcs) {
    if (funcs) {
      funcs.forEach((func) => {
        // 去掉形参表达式
        if (func.functionName.match(/\w+/)) {
          [func.functionName] = func.functionName.match(/\w+/);
        }
      });
    }
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((project) => project.createRandomIntegrationVersion(benchmark.files, benchmark.config))
      .then((res) => {
        projectVersion = res;
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'get');
  common.should.be.tester(uri, url, 'get');

  common.should.be.user(uri, invokeFilesUrl, 'put');
  common.should.be.tester(uri, invokeFilesUrl, 'put');

  common.should.be.user(uri, stubUrl, 'put');
  common.should.be.tester(uri, stubUrl, 'put');

  // 正常获取文件下元素
  it('it should GET function invokes successfully', function (done) {
    projectVersion.getAllFunctions(benchmark)
      .then((allElements) => {
        allElements.forEach((element) => {
          if (element.functionName === 'main') {
            mainFuncId = element.functionId;
          }
        });
        return new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
          chai.request(uri)
            .get(url(mainFuncId))
            .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
            .end((err, res) => {
              res.should.have.status(200);
              common.should.be.invokeMessage(res.body);
              let key = [];
              removeFuncParams(res.body.functions);
              res.body.functions.forEach((invokeFunc) => {
                switch (invokeFunc.functionName) {
                  case 'func3':
                    fileAlternativeFunc = invokeFunc;
                    break;
                  case 'func4':
                    key = key.concat(['mainInvokes', 'fileChangedMainInvokes']);
                    break;
                  case 'func5':
                    key = key.concat(['fileChangedMainInvokes', 'mainInvokes']);
                    break;
                  default:
                    break;
                }
              });
              benchmark.result[key[0]].functions.push(
                { ...benchmark.result.func3 }
              );
              benchmark.result[key[0]].functions.push(benchmark.result.func4);
              benchmark.result.func3.fileName = benchmark.result.func5.fileName;
              benchmark.result.func3.filePath = benchmark.result.func5.filePath;
              benchmark.result[key[1]].functions.push(
                { ...benchmark.result.func3 }
              );
              benchmark.result[key[1]].functions.push(benchmark.result.func5);
              common.should.be.equal.invokes(res.body, benchmark.result.mainInvokes);
              resolve();
            });
        });
      })
      .then(() => {
        done();
      })
      .catch(done);
  });

  // 正常选择文件
  it('it should change invoked files successfully', function (done) {
    new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
      chai.request(uri)
        .put(invokeFilesUrl(mainFuncId, fileAlternativeFunc.mangledId))
        .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
        .send({
          originalFileId: fileAlternativeFunc.fileId,
          fileId: fileAlternativeFunc.files.find(
            (file) => file.fileId !== fileAlternativeFunc.fileId
          ).fileId,
        })
        .end((err, res) => {
          res.should.have.status(204);
          resolve();
        });
    })
      .then(() => new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
        chai.request(uri)
          .get(url(mainFuncId))
          .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(200);
            removeFuncParams(res.body.functions);
            common.should.be.invokeMessage(res.body);
            common.should.be.equal.invokes(res.body, benchmark.result.fileChangedMainInvokes);
            resolve();
          });
      }))
      .then(() => {
        done();
      })
      .catch(done);
  });

  it('it should stub function successfully', function (done) {
    let originalData;
    let stubFuncId;
    let toFuncMangledId;
    let toFuncName;
    new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
      chai.request(uri)
        .get(url(mainFuncId))
        .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
        .end((err, res) => {
          res.should.have.status(200);
          removeFuncParams(res.body.functions);
          originalData = res.body;
          originalData.functions.forEach((invoke) => {
            delete invoke.id;
            // 去掉形参表达式
            if (invoke.functionName.match(/\w+/)) {
              [invoke.functionName] = invoke.functionName.match(/\w+/);
            }
            if (invoke.functionName === 'func1') {
              stubFuncId = invoke.functionId;
              toFuncMangledId = invoke.toFuncMangledId;
              toFuncName = invoke.toFuncName;
            }
          });
          resolve();
        });
    })
      .then(() => new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
        chai.request(uri)
          .put(stubUrl(mainFuncId))
          .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
          .send({
            stubStatus: true,
            functionId: stubFuncId,
            mangledId: toFuncMangledId,
            functionName: toFuncName,
          })
          .end((err, res) => {
            res.should.have.status(204);
            resolve();
          });
      }))
      .then(() => new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
        chai.request(uri)
          .get(url(mainFuncId))
          .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(200);
            removeFuncParams(res.body.functions);
            common.should.be.invokeMessage(res.body);
            common.should.be.equal.invokes(res.body, benchmark.result.stubedMainInvokes);
            resolve();
          });
      }))
      .then(() => new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
        chai.request(uri)
          .put(stubUrl(mainFuncId))
          .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
          .send({
            stubStatus: false,
            functionId: stubFuncId,
            mangledId: toFuncMangledId,
            functionName: toFuncName,
          })
          .end((err, res) => {
            res.should.have.status(204);
            resolve();
          });
      }))
      .then(() => new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
        chai.request(uri)
          .get(url(mainFuncId))
          .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(200);
            removeFuncParams(res.body.functions);
            common.should.be.invokeMessage(res.body);
            common.should.be.equal.invokes(res.body, originalData);
            resolve();
          });
      }))
      .then(() => {
        done();
      })
      .catch(done);
  });

  it('it should add manual stub successfully', function (done) {
    done();
  });
});
